<?php
namespace Framework;

/**
 * Class Session handles session management.
 */
class Session
{
    /**
     * Starts the session if it has not already started.
     * @return void
     */
    public static function start()
    {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
    }

    /**
     * Sets a session variable.
     * @param string $key The key for the session variable.
     * @param mixed $value The value to be stored.
     * @return void
     */
    public static function set($key, $value)
    {
        $_SESSION[$key] = $value;
    }

    /**
     * Retrieves a session variable.
     * @param string $key The key for the session variable.
     * @param mixed $default The default value to return if the session variable is not set.
     * @return mixed
     */
    public static function get($key, $default = null)
    {
        return isset($_SESSION[$key]) ? $_SESSION[$key] : $default;
    }

    /**
     * Checks if a session variable is set.
     * @param string $key The session variable key.
     * @return bool True if set, false otherwise.
     */
    public static function has($key)
    {
        return isset($_SESSION[$key]);
    }

    /**
     * Clears a session variable.
     * @param string $key The session variable key to clear.
     * @return void
     */
    public static function clear($key)
    {
        if (isset($_SESSION[$key])) {
            unset($_SESSION[$key]);
        }
    }

    /**
     * Clears all session variables.
     * @return void
     */
    public static function clearAll()
    {
        session_unset();
        session_destroy();
    }

    /**
     * Set a flash message.
     * @param string $key The key for the message.
     * @param string $message The message content.
     * @return void
     */
    public static function setFlashMessage($key, $message)
    {
        self::set('flash_' . $key, $message);
    }

    /**
     * Show a flash message.
     * @param string $key The key for the message.
     * @param mixed $default The default value if the key does not exist.
     * @return string The message content.
     */
    public static function getFlashMessage($key, $default = null)
    {
        $message = self::get('flash_' . $key, $default);
        self::clear('flash_' . $key);
        return $message;
    }
}